﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Slam.Configuration;
using Slam;
using System.Xml.Linq;
using Microsoft.SharePoint;
using System.Web;
using System.Data.Linq;

namespace SlamCms.SharePoint.Publishing.Services
{
	public class UserService
	{
		private string GetUserNameQuery
		{
			get
			{
				return "select Name from [{0}].[User] where UserName like '%{1}' ";
			}
		}

		private string _dataSchema;
		private string _connectionString;
		private DataMapping _currentDataMapping;
		private IConfigurationManager _configuration;

		public UserService()
		{
			_configuration = ComponentService.GetInstance<IConfigurationManager>();

			_currentDataMapping = _configuration.DataMapping;
			string siteCollection = SPContext.GetContext(HttpContext.Current).Site.ServerRelativeUrl.TrimStart('/');
			if (!String.IsNullOrEmpty(siteCollection) && _configuration.DataMappings.ContainsKey(siteCollection))
			{
				_currentDataMapping = _configuration.DataMappings[siteCollection];
			}
			if (_configuration is XmlConfigurationManager)
			{
				_dataSchema = ((XmlSqlDataMapping)_currentDataMapping).GetDataSchema();
				_connectionString = ((XmlSqlDataMapping)_currentDataMapping).GetConnectionString();
			}

			ConnectionStringSection connectionStringSection = _configuration.GetSection<ConnectionStringSection>("ConnectionStrings");

			if (String.IsNullOrEmpty(_connectionString))
			{
				_connectionString = connectionStringSection.Default;
			}
			else
			{
				_connectionString = connectionStringSection.GetConnectionString(_connectionString);
			}
		}

		public string GetUserName(string username)
		{
			DataContext context = new DataContext(_connectionString);
			return context.ExecuteQuery<string>(String.Format(GetUserNameQuery, _dataSchema, username)).FirstOrDefault() ?? "No Name";
		}
	}
}
